import { NodeProps } from '@/components/workflow/types'
import { CaretRightOutlined, CodepenOutlined } from '@ant-design/icons'
import type { FC } from 'react'
import React, { useEffect, useState } from 'react'
import '../style.less'
import CodeEdit from './code'
import { useWorkFlowStore } from '@/store/workflowStore'
import { Button, Collapse, theme } from 'antd'
import RunDrawer from '../components/RunDrawer'
import { getCodeDefaultParams } from './default'
import type { CollapseProps } from 'antd'
import CollapseNodeComponent from '../components/CollapseNodeComponent'
import InputContNew from './component/InputContOld'
import ExportationCont from './component/ExportationCont'
import IdeDialog from './component/IdeDialog'

const CodePanel: FC<NodeProps<any>> = ({ id, data }) => {

  const { flowVariables, setFlowVariables } = useWorkFlowStore()
  const [ideVisible, setIdeVisible] = useState(false);
  const { token } = theme.useToken()
  const panelStyle: React.CSSProperties = {
    marginBottom: 24,
    background: token.colorFillAlter,
    borderRadius: token.borderRadiusLG,
    border: 'none'
  }

  const createCollapseItem = (key: string, label: JSX.Element, children: JSX.Element) => ({
    key,
    label,
    children,
    style: panelStyle
  })

  const [info, setInfo] = useState({ ...getCodeDefaultParams() }) as any
  console.log("getCodeDefaultParams===>info", info)
  const getSourceOptions = info => {
    return info.inputList
      ? info.inputList.filter(input => input.variable).map(input => ({ value: input.variable, label: input.variable }))
      : []
  }

  const [sourceOptions, setSourceOptions] = useState<{ value: string; label: string }[]>(getSourceOptions(info))
  const editData = e => {
    const obj = { ...info, ...e }
    setInfo(obj)
    setFlowVariables(id, data.title, obj)
    setSourceOptions(getSourceOptions(obj))
  }

  // 溯源信息处理后再加载页面内容
  const [loadContent, setLoadContent] = useState(false)
  useEffect(() => {
    setLoadContent(true)
  }, [sourceOptions])


  /* 输入 */
  const OldInputItems: CollapseProps['items'] = [
    createCollapseItem(
      '6',
      <CollapseNodeComponent
        title="输入"
        tooltipText="输入需要添加到代码的变量，代码中可直接引用此处添加的变量"
      ></CollapseNodeComponent>,
      <>{loadContent && <InputContNew info={info} sourceOptions={sourceOptions} editData={editData} />}</>
    )
  ]

  /* 输出 */
  const ExportationItems: CollapseProps['items'] = [
    createCollapseItem(
      '5',
      <CollapseNodeComponent title="输出" tooltipText="代码节点输出结果"></CollapseNodeComponent>,
      <ExportationCont info={info} editData={editData} />
    )
  ]

  useEffect(() => {
    console.log("flowVariables ====>", flowVariables)
    if (flowVariables && flowVariables[data.id]) {
      const obj = {
        ...info,
        ...flowVariables[data.id]
      }
      console.log("flowVariables  obj====>", obj)
      setInfo(obj)
      /* 单节点运行弹窗 */
      if (flowVariables[data.id].runDrwaerHid === 1) {
        setrunDrawerHid(true)
      }
      setSourceOptions(getSourceOptions(obj))
    }
  }, [flowVariables])
  /* 单节点弹窗状体啊 */
  const [runDrawerHid, setrunDrawerHid] = useState(false)
  const showDrawer = () => {
    setrunDrawerHid(true)
  }

  const collapseProps = {
    bordered: false,
    expandIcon: ({ isActive }) => <CaretRightOutlined rotate={isActive ? 90 : 0} />,
    style: { background: token.colorBgContainer }
  }

  const genExtra = () => (
    <Button type="link" block
      style={{ position: 'relative', top: '-4px' }}
      icon={<CodepenOutlined />}
      onClick={(e) => {
        e.stopPropagation();
        setIdeVisible(true)
      }}
    >
      在IDE中编辑
    </Button>
  );

  return (
    <div className="workflow-common-panel">
      <div className="common-panel-desc">编写代码，处理输入变量来生成返回值</div>

      {/* 输入 */}
      <div className="lim_cardMarBot" key="6">
        <Collapse {...collapseProps} defaultActiveKey="6" items={OldInputItems} />
      </div>

      {/* 代码块部分 */}
      <div className="nodrag cursor-default">
        <Collapse
          bordered={false}
          defaultActiveKey={['1']}
          expandIcon={({ isActive }) => <CaretRightOutlined rotate={isActive ? 90 : 0} />}
          className="bg-[#fafafa]"
          items={[
            {
              key: '1',
              label: <CollapseNodeComponent title="代码块" tooltipText="参考示例代码编写一个函数结构，可以直接使用输入参数中的变量，并通过return一个对象来输出处理结果。此功能不支持编写多个函数，并请务必以对象的形式return"></CollapseNodeComponent>,
              children: (
                <>
                  <CodeEdit editData={editData} info={info} />
                </>
              ),
              extra: genExtra(),
            }
          ]}
        />
      </div>

      {/* 输出 */}
      <div className="lim_cardMarBot " key="5" style={{ marginTop: '24px' }}>
        <Collapse {...collapseProps} defaultActiveKey="5" items={ExportationItems} />
      </div>

      {/* 抽屉 */}
      {runDrawerHid && <RunDrawer nodeData={info} openDef={runDrawerHid} setrunDrawerHid={setrunDrawerHid}></RunDrawer>}

      {/* IDE编辑器 */}
      {
        ideVisible && (
          <IdeDialog
            editData={editData} info={info}
            closeIde={_ => setIdeVisible(false)}
          ></IdeDialog>
        )
      }
    </div>
  )
}

export default React.memo(CodePanel)
